package cn.lls.service.impl;

import cn.lls.base.exception.LlsException;
import cn.lls.base.result.ResultCode;
import cn.lls.dao.PermissionDao;
import cn.lls.entity.sys.PermissionEntity;
import cn.lls.service.IPermissionService;
import cn.lls.vo.permission.MenuVO;
import cn.lls.vo.permission.Meta;
import cn.lls.vo.permission.PermissionVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 划水艺术家
 * @since 2022-11-15
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionDao, PermissionEntity> implements IPermissionService {


    @Override
    public List<PermissionVO> getPermissionsByRoleId(Long roleId){
        return this.baseMapper.getPermissionsByRoleId(roleId);
    }



    /*
       增加权限即功能
    */
    public void addPermission(PermissionEntity permission) {
        upsert(permission);
        try{
            int insert = this.baseMapper.insert(permission);
            if (insert == 0)
                throw new LlsException(500, "数据库异常");
        } catch (Exception e){
            throw new LlsException(500, "数据库异常");
        }
    }

    /*
      修改权限即功能
   */
    @Override
    public void updatePermission(PermissionEntity permission) {
        upsert(permission);
        if (permission.getPermissionId() == null || this.baseMapper.getPermissionVOById(permission.getPermissionId()) == null)
            throw new LlsException(ResultCode.PARAM_ERROR, "数据异常，不存在当前Id的权限");
        try{
            int update = this.baseMapper.updateById(permission);
            if (update == 0)
                throw new LlsException(ResultCode.DATA_ERROR, "数据异常");
        } catch (Exception e){
            throw new LlsException(ResultCode.DATA_ERROR, "数据异常");
        }
    }

    /*
        删除权限
   * */
    @Override
    public void delPermission(Integer permissionId) {
        delStop(permissionId, "删除");
    }

    /*
    * 删除、停止使用权限的公共操作
    * */
    private void delStop(Integer permissionId, String model){
        List<PermissionVO> permissionVOByParentId = this.baseMapper.getPermissionVOByParentId(permissionId);
        if (permissionVOByParentId != null && permissionVOByParentId.size() > 0)
            throw new LlsException(ResultCode.EXE_ERROR, "当前权限有子权限，无法" + model);
        try{
            int delete = this.baseMapper.deleteById(permissionId);
            if (delete == 0)
                throw new LlsException(ResultCode.DATA_ERROR, "数据异常");
        } catch (Exception e){
            throw new LlsException(ResultCode.DATA_ERROR, "数据异常");
        }
    }

    /*
        停止使用某权限
   * */
    @Override
    public void stopPermission(Integer permissionId) {
        delStop(permissionId, "停止使用");
    }

    /*
        开起某权限
     */
    @Override
    public void startPermission(Integer permissionId) {
        try {
            int i = this.baseMapper.changeLogic(permissionId, 0);
            if (i == 0)
                throw new LlsException(ResultCode.DATA_ERROR, "数据异常");
        } catch (Exception e){
            throw new LlsException(ResultCode.DATA_ERROR, "数据异常");
        }
    }

    /*
        增加权限与修改权限的公共操作
     */
    private void upsert(PermissionEntity permission){
        // 查询 父 id
        Integer parentId = permission.getParentId();
        if (parentId != null){
            PermissionVO perTemp = this.baseMapper.getPermissionVOById(parentId);
            if (perTemp == null){
                throw new LlsException(ResultCode.DATA_ERROR, "数据传参错误，不存在当前父Id");
            }
        }
    }

    /**
    *   根据 Id 获取权限
    *  @Params
    *  @Return
    */
    @Override
    public PermissionVO getPermissionById(Integer permissionId) {
        PermissionEntity permission = this.baseMapper.selectById(permissionId);
        System.out.println("per = " + permission);
        if (permission == null) return null;
        PermissionVO permissionVO = new PermissionVO();
        BeanUtils.copyProperties(permission, permissionVO);
        dfs(permissionVO);
        return permissionVO;
    }

    /*
       获取所有权限
    */
    @Override
    public List<PermissionVO> getAllPermission() {
        List<PermissionVO> allParent = this.baseMapper.getAllParent();
        for (PermissionVO permissionVO: allParent){
            dfs(permissionVO);
        }
        return allParent;
    }


    /*
    获取超级管理员的菜单
     */
    @Override
    public List<MenuVO> getSuperAdminMenu() {
        List<PermissionVO> allParent = this.baseMapper.getSuperAdminAllParent();
        for (PermissionVO permissionVO: allParent){
            dfs(permissionVO);
        }
        return allParent.stream().map(this::permission2Menu).collect(Collectors.toList());
    }

    /*
    获取所有单位管理员的菜单
     */
    @Override
    public List<MenuVO> getCompanyAdminMenu() {
        List<PermissionVO> allParent = this.baseMapper.getCompanyAdminAllParent();
        for (PermissionVO permissionVO: allParent){
            dfs(permissionVO);
        }
        return allParent.stream().map(this::permission2Menu).collect(Collectors.toList());
    }


    /*
    获取某个角色的所有菜单
     */
    @Override
    public List<MenuVO> getMenusByRoleId(Long roleId){
        List<PermissionVO> allParent = this.baseMapper.getPermissionsByRoleId(roleId);
        for (PermissionVO permissionVO: allParent){
            dfs(permissionVO);
        }
        return allParent.stream().map(this::permission2Menu).collect(Collectors.toList());
    }


    /*
    权限转换为 vue-router 路由形式
     */
    private MenuVO permission2Menu(PermissionVO item){
        MenuVO menuVO = new MenuVO();
        menuVO.setPath(item.getUrl());
        menuVO.setComponent(item.getComponent());
        menuVO.setName(item.getPermissionName());
        menuVO.setRedirect(item.getRedirect());
        menuVO.setHidden(item.getHidden());
        menuVO.setMeta(new Meta(item.getPermissionName(), item.getIcon()));
        if (item.getChildrenPermissions() != null && item.getChildrenPermissions().size() > 0)
            menuVO.setChildren(item.getChildrenPermissions().stream().map(this::permission2Menu).collect(Collectors.toList()));
        return menuVO;
    }

    /*
        对某个权限深度优先搜索，找到他的所有子权限
     */
    private void dfs(PermissionVO permissionVO){
        List<PermissionVO> permissionVOs = this.baseMapper.getPermissionVOByParentId(permissionVO.getPermissionId());
        if (permissionVOs != null && permissionVOs.size() > 0) {
//            permissionVO.setHasChildren(true);
            permissionVO.setChildrenPermissions(permissionVOs);
            for (PermissionVO permissionVO1: permissionVOs)
                dfs(permissionVO1);
        }
    }

}
